package com.qfedu.openapi.web.master.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qfedu.openapi.web.master.dao.user.UserDAO;
import com.qfedu.openapi.web.master.entity.User;
import com.qfedu.openapi.web.master.service.UserService;
import com.qfedu.openapi.web.master.vo.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("/userService")
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDAO userDAO;
    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public User findUserById(Integer id) {
        return userDAO.findUserById(id);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public List<User> findAllUser() {
        return userDAO.findAllUser();
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public PageInfo<User> findAllUser(PageVo pageVo) {
        PageHelper.startPage(pageVo.getPage(),pageVo.getLimit());
        List<User> users = userDAO.findAllUser();
        return new PageInfo<User>(users);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public PageInfo<User> findAllUser(PageVo pageVo, User user) {
        PageHelper.startPage(pageVo.getPage(),pageVo.getLimit());
        List<User> users = userDAO.findAllUsersByCondition(user);
        return new PageInfo<User>(users);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addUser(User user) {
        return userDAO.insertUser(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delUser(Integer[] ids) {
        return userDAO.deleteUser(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(User user) {
        return userDAO.updateUser(user);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public boolean checkUser(User user) {
        String name = user.getName();
        String password = user.getPassword();
        // 根据user对象中的用户名，去数据库中查找有没有对应的用户
        // 如果没有查询到对应的用户，则返回false
        User dbUser = userDAO.getUserByName(name);
        if (dbUser == null) {
            return false;
        }
        // 如果查询到了用户，则比较数据库中的用户的密码和当前user对象中的密码是否一致
        // 如果密码一致，则登录成功，否则登录失败
        String dbPassword = dbUser.getPassword();
        if(dbPassword.equals(password)){
            return true;
        }
        return false;
    }
}
